package com.moli.iov.task.remoting.op.reponse;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.task.constants.Constants;
import com.moli.iov.task.model.dto.StorageInfoDto;
import com.moli.iov.util.HttpUtil;
import com.moli.iov.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  OP门店数据
 * </p>
 *
 * @Auther: zql
 * @Date: 2019/1/7 14:39
 */
@Slf4j
@Component
public class StorageResponseHandler {

    @Autowired
    private TokenResponseHandler tokenRequestHandler;

    @Value("${op_query_storage_url}")
    private String opQueryStorageUrl;

    @Value("${op_channel_val}")
    private String opChannelVal;

    /**
     * 获取OP 门店数据
     * @return
     */
    public List<StorageInfoDto>  queryOpStorageInfo() throws Exception {
        String token = tokenRequestHandler.getToken();
        return this.queryOpStorageInfoReal(token);
    }

    /**
     * 真实获取OP 门店数据
     * @param token
     * @return
     * @throws IOException
     */
    public List<StorageInfoDto> queryOpStorageInfoReal(String token) throws Exception {
        Map<String, String> header = Maps.newHashMap();
        header.put("token", token);
        header.put("channel", opChannelVal);

        String result = HttpUtil.get(opQueryStorageUrl, header);

        if(StringUtil.isBlank(result)){
            log.error("真实获取OP 门店数据失败， OP返回空");
            throw new BusinessException("获取OP门店数据异常");
        }

        JSONObject jsonObject = JSONObject.parseObject(result);
        if(Constants.OP_SUCCESS != jsonObject.getInteger("code")){
            log.error("真实获取OP 门店数据失败，OP返回状态非200 token:{} 出参：{}",token, jsonObject);
            throw new BusinessException("真实获取OP 门店数据失败，OP返回状态非200");
        }

        return JSONObject.parseArray(jsonObject.getString("data"), StorageInfoDto.class);

    }

}
